package com.jsh.common.util;

import com.alibaba.fastjson.util.IOUtils;
import org.apache.commons.lang3.StringUtils;

import java.io.*;
import java.lang.reflect.Array;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;

/**
 * @Author JiangYaoFeng
 * 2021/12/3 13:28
 * 文件处理的工具类
 */

public final class FileUtils {

    /**
     * create by: JiangYaoFeng
     * description: 将多个文件压缩成一个文件   注:此方法执行失败会自动清理未完成的压缩文件
     *
     * @param zipPath 压缩文件输出路径
     * @param files   被压缩文件路径集合
     * @return 整体是否成功
     */
    public static boolean filesToZip(String zipPath, String[] files) {
        List<String> collect = Arrays.stream(files).collect(Collectors.toList());
        return filesToZip(zipPath, collect);
    }

    public static boolean filesToZip(String zipPath, List<String> files) {

        File zipFile = new File(zipPath);


        FileOutputStream fileOutputStream = null;
        ZipOutputStream zipOutputStream = null;
        FileInputStream fileInputStream = null;
        try {
            if (!zipFile.exists()) {
                zipFile.createNewFile();
            }
            fileOutputStream = new FileOutputStream(zipFile);
            zipOutputStream = new ZipOutputStream(fileOutputStream);

            for (String filePath : files) {
                File file = new File(filePath);
                if (file == null && !file.exists()) {
                    return false;
                }
                fileInputStream = new FileInputStream(file);
                ZipEntry zipEntry = new ZipEntry(file.getName());
                zipOutputStream.putNextEntry(zipEntry);
                org.apache.commons.io.IOUtils.write(org.apache.commons.io.IOUtils.toByteArray(fileInputStream),zipOutputStream);
                zipOutputStream.closeEntry();
                fileInputStream.close();
            }
            zipOutputStream.close();
        } catch (Exception e) {
            if (zipFile.exists()) {
                zipFile.delete();
            }
            e.printStackTrace();
        } finally {
            IOUtils.close(fileOutputStream);
            IOUtils.close(fileInputStream);
            IOUtils.close(zipOutputStream);
        }
        return true;

    }



}
